package com.atguigu.mall.order.config;

import com.baomidou.mybatisplus.extension.api.R;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.amqp.support.converter.MessageConverter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

import javax.annotation.PostConstruct;

/**
 * @author zststart
 * @create 2022-06-14 18:05
 */
@Configuration
public class MyRabbitConfig {
//    @Autowired
    RabbitTemplate rabbitTemplate;
    //TODO
    @Primary
    @Bean
    public RabbitTemplate rabbitTemplate(ConnectionFactory connectionFactory){
        RabbitTemplate rabbitTemplate = new RabbitTemplate(connectionFactory);
        this.rabbitTemplate = rabbitTemplate;
        rabbitTemplate.setMessageConverter(messageConverter());
        initRabbitTemplate();
        return rabbitTemplate;
    }

    @Bean
    public MessageConverter messageConverter(){
        return new Jackson2JsonMessageConverter();//给容器里放一个json的转换包
    }

    /**
    //定制rabbitTemplate
    @PostConstruct//对象创建完成后执行这个方法
     **/
    public void initRabbitTemplate(){
        rabbitTemplate.setConfirmCallback(new RabbitTemplate.ConfirmCallback() {
            @Override
            public void confirm(CorrelationData correlationData, boolean ack, String cause) {
                //当前消息的唯一关联数据，消息的唯一id； 消息是否成功收到  ； 失败的原因
                //只要消息抵达broker，就会ack返回true
            }
        });

        //设置消息抵达队列的确认回调，只要消息没有投递给指定队列，就触发这个失败回调
        rabbitTemplate.setReturnCallback(new RabbitTemplate.ReturnCallback() {
            @Override
            public void returnedMessage(Message message, int replyCode, String replyText, String exchange, String routingKey) {
                //投递失败的消息详细信息；回复状态码，回复文本内容；当时这个消息发送给哪个路由器，用的哪个路由key
            }
        });
    }

}
